package cn.hp.controller;

import cn.hp.common.constant.Constant;
import cn.hp.entity.Department;
import cn.hp.entity.DictType;
import cn.hp.service.DepartmentService;

import cn.hp.util.util.RandomNumber;
import cn.hp.util.util.RedisUtil;
import cn.hp.util.util.Result;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@RestController
@RequestMapping("/api/department")
@Api(value = "/department",tags = "部门管理")
public class DepartmentController {

    @Autowired
    private DepartmentService departmentService;

      @Resource
    private RedisUtil redisUtil;

    @GetMapping
    @ApiOperation(value = "查询",notes = "查询所有部门")
    public Result find(Department department) {
         if (!redisUtil.hasKey(Constant.DEPARTMENT_KEY)) {
             List<Department> list = departmentService.selectDepartment(department);
             redisUtil.set(Constant.DEPARTMENT_KEY, JSON.toJSONString(list), RandomNumber.randomNum(null));
         }
          Object obj=redisUtil.get(Constant.DEPARTMENT_KEY);
          List<Department> departments=JSON.parseArray((String) obj,Department.class);
          return Result.success(departments);
    }

    @GetMapping("/page")
    @ApiOperation(value = "分页查询",notes = "分页查询所有部门")
    public Result page(Department department, @RequestParam(value = "page", defaultValue = "1") Integer page, @RequestParam(value = "limit", defaultValue = "10") Integer limit) {
        PageInfo<Department> pageInfo = departmentService.selectDepartment(department, page, limit);
        return Result.success(pageInfo);
    }

    @PostMapping
     @ApiOperation(value = "新增",notes = "新增部门")
    public Result insert(@RequestBody Department department) {
        redisUtil.del(Constant.DEPARTMENT_KEY);
        int i = departmentService.insertDepartment(department);
        return i > 0 ? Result.success("新增成功") : Result.error("新增失败");
    }

    @PutMapping
    @ApiOperation(value = "修改",notes = "修改部门")
    public Result update(@RequestBody Department department) {
        redisUtil.del(Constant.DEPARTMENT_KEY);
        int i = departmentService.updateDepartment(department);
        return i > 0 ? Result.success("修改成功") : Result.error("修改失败");
    }

    @DeleteMapping("/{id}")
    @ApiOperation(value = "删除",notes = "删除部门")
    public Result delete(@PathVariable Integer id) {
        redisUtil.del(Constant.DEPARTMENT_KEY);
        int i = departmentService.deleteDepartmentById(id);
        return i > 0 ? Result.success("删除成功") : Result.error("删除失败");
    }
}